package cn.creat.ht.service.impl;

import cn.creat.ht.pojo.Page;
import cn.creat.ht.service.InforGetService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Wuhaoze on 2017/5/6 0006.
 */
public class InforGetServiceImpl implements InforGetService {


    public String getTalkInfor() throws Exception {
        JSONObject jsonObject = JSONObject.fromObject(sendGet(MAIN_URL+"1"));
        jsonObject.put("pageNum",1);
        jsonObject.put("hasNext",hasNext(2));
        return jsonObject.toString();
    }

    public String getArticle(String id) throws Exception {
        System.out.println(VIEW_URL+id);
        return sendGet(VIEW_URL+id);
    }

    public String getNextPage(int pageNum) throws Exception {
        return sendGet(MAIN_URL+String.valueOf(pageNum+1));
    }

    public String getPrePage(int pageNum) throws Exception {
        if(pageNum <= 1){
            return sendGet(MAIN_URL+"1");
        }else {
            return sendGet(MAIN_URL+String.valueOf(pageNum-1));
        }
    }

    private String sendGet(String url) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity,"utf-8");
    }
    private boolean hasNext(int pageNum) throws IOException {
        JSONObject jsonObject = JSONObject.fromObject(sendGet(MAIN_URL+String.valueOf(pageNum)));
        JSONArray data = jsonObject.getJSONArray("data");
        if(data.size()>0){
            return true;
        }else {
            return false;
        }
    }
}
